//
//  RenHePartnerDetailController.m
//  BigToBig
//
//  Created by yi liu on 16/8/1.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "RenHePartnerDetailController.h"
#import "InvestorDetailMessageView.h"
#import "DetailPartnerCell.h"
#import "BasicInfoTableViewCell.h"
#import "ProjectDetailViewController.h"
#import "FocusProjectModel.h"
#import "FocusPartnerModel.h"

@interface RenHePartnerDetailController ()
<
    UITableViewDelegate,
    UITableViewDataSource
>

@property (nonatomic , strong)InvestorDetailMessageView *investorDetailMessageView;

@property (nonatomic , strong)UITableView *mainTableView;


@property (nonatomic , strong)UIButton *focusButton;
@property (nonatomic , strong)UIButton *invitePartnerButton;
@property (nonatomic , strong)NSArray *planArray;
@property (nonatomic , strong)NSArray *content;
@property (nonatomic , strong)NSMutableArray *focusModelArr;
@property (nonatomic , strong)NSMutableArray *partnerModelArr;
@property (nonatomic , strong)NSString *info;

@property (nonatomic , assign)BOOL isSelected;
@property (nonatomic , assign)BOOL isFocusSelected;
@property (nonatomic , assign)NSInteger focusProjectCount;
@property (nonatomic , assign)NSInteger isFocused;

@end

@implementation RenHePartnerDetailController

- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    [self ifFocusThisGuy];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self createData];
    [self LoadPartnerInformation];
    [self focusProjectModel];
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    titleLab.text = @"基本信息";
    titleLab.textColor = [UIColor whiteColor];
    [self setBackBar];
    titleLab.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLab;
    [self createView];
    
}

#pragma mark 创建数据
- (void)createData{
    self.planArray = @[@"关注领域",@"关注城市",@"每年计划投资项目个数"];
    if ([[self.renhe.selfIntroduction stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]!= 0) {
        self.info = self.renhe.selfIntroduction;
    }else{
        self.info = @"还没有写自我介绍...";
    }

    self.focusProjectCount = 0;
    self.content = @[@"最高学历",@"关注的项目",@"创业伙伴"];
}
- (void)LoadPartnerInformation{
    self.partnerModelArr = [NSMutableArray array];
    NSDictionary *params = @{@"partner_id":(NSString *)_renhe.partnerId};
    NSString *urlStr = [NSString stringWithFormat:@"http://61.135.176.43:6080/bigtobig/partner/get_partner_relations_by_partner?partner_id=%@&limit=10&offset=0",_renhe.partnerId];
    [HttpTool textHTMLPostWithURL:urlStr params:params success:^(id json) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSArray *createdProjectsArr = [dict objectForKey:@"PartnerRelationList"];
        NSLog(@"%@",createdProjectsArr);
        NSMutableArray *relationUserIdArr = [NSMutableArray array];
        for (NSDictionary *dic in createdProjectsArr) {
            NSString *relationUserId = [dic objectForKey:@"relationUserId"];
            [relationUserIdArr addObject:relationUserId];
            
            FocusPartnerModel *createdProjectModel = [FocusPartnerModel FocusPartnerModelWithDict:dic];
            [self.partnerModelArr addObject:createdProjectModel];
            [self.mainTableView reloadData];
        }

        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}
#pragma mark - Load 关注项目  数据
- (void)focusProjectModel{
    self.focusModelArr = [NSMutableArray new];
    
    NSDictionary *params = @{@"user_id":(NSString *)_renhe.userId};
    NSString *urlStr = [NSString stringWithFormat:@"http://61.135.176.43:6080/bigtobig/notice_project/show_project?user_id=%@&offset=0&limit=10",_renhe.userId];
    [HttpTool textHTMLPostWithURL:urlStr params:params success:^(id json) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSNumber *count = [dict objectForKey:@"count"];
        NSArray *noticeProjectsArr = [dict objectForKey:@"notice_projects"];
        for (NSDictionary *dic in noticeProjectsArr) {
            FocusProjectModel *focusModel = [FocusProjectModel FocusProjectModelWithDict:dic];
            [self.focusModelArr addObject:focusModel];
        }
        self.focusProjectCount = self.focusProjectCount + count.integerValue;
        [self.mainTableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}
#pragma mark 导航栏左右Button
- (void)setBackBar{
    
    BackButton *backBtn=[BackButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 44, 44);
    [backBtn addTarget:self action:@selector(backController:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn.imageView setContentMode:UIViewContentModeLeft];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    [self.navigationItem setHidesBackButton:YES animated:YES];
    
}

- (void)backController:(UIButton *)button{
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 创建View
- (void)createView{
    self.isSelected = NO;
    self.isFocusSelected = NO;
    
    self.investorDetailMessageView = [[InvestorDetailMessageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 150)];
    self.investorDetailMessageView.nameLabel.text = self.renhe.name;
    self.investorDetailMessageView.jobLabel.text = self.renhe.companyName;
    self.investorDetailMessageView.focusLabel.text = [NSString stringWithFormat:@"%@%@",@"  已关注 : ",self.renhe.relation_user_count];
    self.investorDetailMessageView.funsLabel.text = [NSString stringWithFormat:@"%@%@",@"  粉丝 : ",self.renhe.relation_project_count];
    self.investorDetailMessageView.backgroundColor = [UIColor whiteColor];
    
    //头像
    [self.investorDetailMessageView.headImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://61.135.176.43:6080/data/HeadPortrait/%@",self.renhe.headImage]] placeholderImage:[UIImage imageNamed:@"touxiang"]];
    
    self.investorDetailMessageView.groupLabel.text = @"创业伙伴";
    // 主tableView
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
    self.mainTableView.tableHeaderView = self.investorDetailMessageView;
    [self.view addSubview:_mainTableView];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    [self.mainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    [self.mainTableView registerClass:[DetailPartnerCell class] forCellReuseIdentifier:NSStringFromClass( [DetailPartnerCell class ])];
    //    [self.mainTableView registerClass:[InvestorDetailSKSCell class] forCellReuseIdentifier:NSStringFromClass([InvestorDetailSKSCell class])];
    [self.mainTableView registerClass:[BasicInfoTableViewCell class] forCellReuseIdentifier:NSStringFromClass([BasicInfoTableViewCell class])];
//    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    self.mainTableView.tableFooterView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
    self.mainTableView.sectionHeaderHeight = 40;
    self.mainTableView.sectionFooterHeight = 0;
    
    // 关注按钮
    self.focusButton = [UIButton  buttonWithType:UIButtonTypeSystem];
    self.focusButton.frame = CGRectMake(kScreenWidth / 2, kScreenHeight - 49, kScreenWidth / 2, 49);
    [self.view addSubview:self.focusButton];
    [self.focusButton setTitle:@"关注" forState:UIControlStateNormal];
    [self.focusButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.focusButton.backgroundColor = COLOR_RGBA(255, 81, 90, 1);
    [self.focusButton addTarget:self action:@selector(focusclick:) forControlEvents:UIControlEventTouchUpInside];
    
    // 邀请伙伴按钮
    self.invitePartnerButton = [UIButton  buttonWithType:UIButtonTypeSystem];
    self.invitePartnerButton.frame = CGRectMake(0, kScreenHeight - 49, kScreenWidth / 2, 49);
    [self.view addSubview:self.invitePartnerButton];
    [self.invitePartnerButton setTitle:@"邀请伙伴" forState:UIControlStateNormal];
    [self.invitePartnerButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.invitePartnerButton.backgroundColor = [UIColor whiteColor];
    
}

#pragma mark 关注

- (void)ifFocusThisGuy{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *follower_id = [userDefault objectForKey:@"userID"];
    NSString *follow_id = (NSString *)self.renhe.userId;
    NSDictionary *params = @{@"follow_id":follow_id,@"follower_id":follower_id};
    [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/relation/show_relation?" params:params success:^(id json) {
        NSString *type = [json objectForKey:@"type"];
        self.isFocused = type.integerValue;
        // 关注按钮
        self.focusButton = [UIButton  buttonWithType:UIButtonTypeSystem];
        self.focusButton.frame = CGRectMake(0, kScreenHeight - 49, kScreenWidth, 49);
        [self.view addSubview:self.focusButton];
        [self.focusButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        if (self.isFocused) {
            
            [self.focusButton setTitle:@"关注" forState:UIControlStateNormal];
            self.focusButton.backgroundColor = COLOR_RGBA(255, 81, 90, 1);
        }
        else{
            [self.focusButton setTitle:@"取消关注" forState:UIControlStateNormal];
            self.focusButton.backgroundColor = [UIColor lightGrayColor];
        }
        
        NSLog(@"%ld",self.isFocused);
        [self.focusButton addTarget:self action:@selector(focusButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
    } failure:^(NSError *error) {
        
        
    }];
    
}

- (void)focusButtonAction:(UIButton *)button{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *follow_id = [userDefault objectForKey:@"userID"];
    NSString *follower_id = (NSString *)self.renhe.userId;
    NSDictionary *params = @{@"follow_id":follow_id,@"follower_id":follower_id};
    if (self.isFocused == 1) {
        [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/relation/add_follower?" params:params success:^(id json) {
            [self.focusButton setTitle:@"取消关注" forState:UIControlStateNormal];
            self.focusButton.backgroundColor = [UIColor lightGrayColor];
            self.isFocused = 0;
            
        } failure:^(NSError *error) {
            
            
        }];
    }
    else{
        
        [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/relation/cancel_follower?" params:params success:^(id json) {
            [self.focusButton setTitle:@"关注" forState:UIControlStateNormal];
            self.focusButton.backgroundColor = COLOR_RGBA(255, 81, 90, 1);
            self.isFocused = 1;
            
        } failure:^(NSError *error) {
            
            
        }];
    }

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == self.mainTableView) {
        if (section == 0) {
            UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, kScreenWidth - 20, 10)];
            titleLabel.text = @"个人简介";
            titleLabel.textAlignment = NSTextAlignmentLeft;
            titleLabel.backgroundColor = COLOR_RGBA(239, 239, 244, 1);
            return titleLabel;
        }
        else {
            UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth - 20, 10)];
            titleLabel.text = @"  ";
            titleLabel.textAlignment = NSTextAlignmentLeft;
            titleLabel.backgroundColor = COLOR_RGBA(239, 239, 244, 1);
            return titleLabel;        }
    }else{
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        // 计算文字的高度
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil];
        // 根据文本的内容和文本的字体进行计算高度
        // 参数一:告诉系统,文本显示的最大范围
        CGFloat width = (self.view.frame.size.width - 40);
        CGRect rect = [self.info boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        // 然后把图片的高和文本的高作为返回值返回
        return rect.size.height + 20;
        
    }
    else if(indexPath.section == 1){
        return 80;
    }
    else{
        return 80;
    }
}

- (void)changeSectionHeight:(NSNotification *)center{
    
    [self.mainTableView reloadData];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    else if (section == 1){
        if (self.isSelected) {
            if (self.isFocusSelected) {
                return 3 + self.focusProjectCount + self.partnerModelArr.count;
            }
            else{
                return 3 + self.partnerModelArr.count;
            }
        }
        else if (self.isFocusSelected){
            return 3 + self.focusProjectCount;
        }
        else{
            return 3;
        }
    }
    else{
        return 3;
    }
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        DetailPartnerCell *partnerCell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([DetailPartnerCell class]) forIndexPath:indexPath];
        partnerCell.partnerLabel.text = self.info;
        
        return partnerCell;
    }
    else if (indexPath.section == 1){
        if (self.isSelected == NO && self.isFocusSelected == NO) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
            cell.textLabel.text = self.content[indexPath.row];
            if(indexPath.row > 0){
                UIImageView *xlImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 15, 15)];
                xlImageView.image = [UIImage  imageNamed:@"xl-button"];
                xlImageView.center = CGPointMake(kScreenWidth - 30, cell.height / 2);
                [cell.contentView addSubview:xlImageView];
            }
            cell.tag = indexPath.row;
            NSLog(@"%ld",cell.tag);
            return cell;
        }
        else if(self.isFocusSelected == YES &&self.isSelected == NO){
            if (indexPath.row < 2 ||indexPath.row == 2 + self.focusProjectCount) {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
                if (indexPath.row < 2) {
                    cell.textLabel.text = self.content[indexPath.row];
                    
                }
                else{
                    cell.textLabel.text = self.content[indexPath.row - self.focusProjectCount];
                }
                cell.tag = indexPath.row;
                return cell;
            }
            else{
                BasicInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BasicInfoTableViewCell class]) forIndexPath:indexPath];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                FocusProjectModel *focusModel = self.focusModelArr[indexPath.row - 2];
                [cell.headPic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.bigtobig.com/%@",focusModel.project_logo]] placeholderImage:[UIImage imageNamed:@"touxiang"]];
                cell.nameLabel.text = focusModel.project_name;
                cell.describe.text = focusModel.project_brief_introduction;

                return cell;
            }
        }
        else if(self.isFocusSelected == NO && self.isSelected == YES){
            if (indexPath.row < 3) {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
                cell.textLabel.text = self.content[indexPath.row];
                cell.tag = indexPath.row;
                return cell;
            }
            else{
                BasicInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BasicInfoTableViewCell class]) forIndexPath:indexPath];
                FocusPartnerModel *partnerModel = self.partnerModelArr[indexPath.row - 3];
                [cell.headPic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.bigtobig.com/%@",partnerModel.headImage]]];
                cell.nameLabel.text = partnerModel.name;
                cell.describe.text = partnerModel.selfIntroduction;
                
                return cell;
            }
        }
        else{
            if (indexPath.row < 2 || indexPath.row == 2 + self.focusProjectCount) {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
                if (indexPath.row < 2) {
                    cell.textLabel.text = self.content[indexPath.row];

                }
                else{
                    cell.textLabel.text = self.content[indexPath.row - self.focusProjectCount];
                }
                cell.tag = indexPath.row;
                return cell;
            }
            else if(indexPath.row >= 2 && indexPath.row < 2 + self.focusProjectCount){
                BasicInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BasicInfoTableViewCell class]) forIndexPath:indexPath];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                FocusProjectModel *focusModel = self.focusModelArr[indexPath.row - 2];
                [cell.headPic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.bigtobig.com/%@",focusModel.project_logo]] placeholderImage:[UIImage imageNamed:@"touxiang"]];
                cell.nameLabel.text = focusModel.project_name;
                cell.describe.text = focusModel.project_brief_introduction;
                
                return cell;
            }
            else{
                BasicInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BasicInfoTableViewCell class]) forIndexPath:indexPath];
                FocusPartnerModel *partnerModel = self.partnerModelArr[indexPath.row - 3];
                [cell.headPic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.bigtobig.com/%@",partnerModel.headImage]]];
                cell.nameLabel.text = partnerModel.name;
                cell.describe.text = partnerModel.selfIntroduction;
                
                return cell;
            }
        }
        
    }
    else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
        cell.textLabel.text = self.planArray[indexPath.row];
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 1) {
        if (indexPath.row == 1) {
            if (self.isFocusSelected == NO) {
                self.isFocusSelected = YES;
                
            }
            else{
                self.isFocusSelected = NO;
            }
        }
        if (indexPath.row == 2|| indexPath.row == 2 + self.focusProjectCount) {
            if (self.isSelected == NO && self.isFocusSelected == NO) {
                self.isSelected = YES;
                
            }
            else if(self.isFocusSelected == YES && indexPath.row == 2 + self.focusProjectCount){
                if (self.isSelected == YES) {
                    self.isSelected = NO;
                }
                else{
                    self.isSelected = YES;
                }
            }
            else{
                if(self.isFocusSelected == YES && indexPath.row == 2){
                    
                }
                else{
                    self.isSelected = NO;
                    
                }
            }
        }
        if (indexPath.row > 1 && indexPath.row <= 1 + self.focusProjectCount && self.isFocusSelected == YES) {
            ProjectDetailViewController *detailVC = [[ProjectDetailViewController alloc]init];
            FocusProjectModel *projectModel = self.focusModelArr[indexPath.row - 2];
            detailVC.project_id = projectModel.project_id;
            [self.navigationController pushViewController:detailVC animated:YES];
        }

    }

    [tableView reloadData];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
